package com.example.flutter_app_echarts;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class BlueToothConnectReceiver extends BroadcastReceiver {
    private OnBleConnectListener onBleConnectListener;

    @TargetApi(Build.VERSION_CODES.ECLAIR)
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        switch (action) {
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                if (onBleConnectListener != null) {
                    onBleConnectListener.onConnect(device);
                }
                System.out.println("BlueToothConnect，蓝牙已连接");
                System.out.println(device.getName());
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                //当直接关闭蓝牙时此处不会被触发，只有当蓝牙未关闭并且断开蓝牙时才会触发
                if (onBleConnectListener != null) {
                    onBleConnectListener.onDisConnect(device);
                }
                System.out.println("BroadcastReceiver，蓝牙已断开");
                System.out.println(device.getName());
                break;
        }

    }

    public interface OnBleConnectListener {
        void onConnect(BluetoothDevice device);

        void onDisConnect(BluetoothDevice device);
    }

    public void setOnBleConnectListener(OnBleConnectListener onBleConnectListener) {
        this.onBleConnectListener = onBleConnectListener;
    }

}
